{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "eac2c62f",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "import math\n",
    "import sys\n",
    "from skimage import io, color, filters\n",
    "import os\n",
    "import math\n",
    "from niqe import niqe\n",
    "import cv2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "d0a5a4e9",
   "metadata": {},
   "outputs": [],
   "source": [
    "def getUCIQE(img_BGR):\n",
    "    #img_BGR = cv2.imread(img)\n",
    "    img_LAB = cv2.cvtColor(img_BGR, cv2.COLOR_BGR2LAB) \n",
    "    img_LAB = np.array(img_LAB,dtype=np.float64)\n",
    "    # Trained coefficients are c1=0.4680, c2=0.2745, c3=0.2576 according to paper.\n",
    "    coe_Metric = [0.4680, 0.2745, 0.2576]\n",
    "    \n",
    "    img_lum = img_LAB[:,:,0]/255.0\n",
    "    img_a = img_LAB[:,:,1]/255.0\n",
    "    img_b = img_LAB[:,:,2]/255.0\n",
    "\n",
    "    # item-1\n",
    "    chroma = np.sqrt(np.square(img_a)+np.square(img_b))\n",
    "    sigma_c = np.std(chroma)\n",
    "\n",
    "    # item-2\n",
    "    img_lum = img_lum.flatten()\n",
    "    sorted_index = np.argsort(img_lum)\n",
    "    top_index = sorted_index[int(len(img_lum)*0.99)]\n",
    "    bottom_index = sorted_index[int(len(img_lum)*0.01)]\n",
    "    con_lum = img_lum[top_index] - img_lum[bottom_index]\n",
    "\n",
    "    # item-3\n",
    "    chroma = chroma.flatten()\n",
    "    sat = np.divide(chroma, img_lum, out=np.zeros_like(chroma, dtype=np.float64), where=img_lum!=0)\n",
    "    avg_sat = np.mean(sat)\n",
    "\n",
    "    uciqe = sigma_c*coe_Metric[0] + con_lum*coe_Metric[1] + avg_sat*coe_Metric[2]\n",
    "    return uciqe"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "4b20b59b",
   "metadata": {},
   "outputs": [],
   "source": [
    "def nmetrics(a):\n",
    "    rgb = a\n",
    "    lab = color.rgb2lab(a)\n",
    "    gray = color.rgb2gray(a)\n",
    "    # UCIQE\n",
    "    c1 = 0.4680\n",
    "    c2 = 0.2745\n",
    "    c3 = 0.2576\n",
    "    l = lab[:,:,0]\n",
    "\n",
    "    #1st term\n",
    "    chroma = (lab[:,:,1]**2 + lab[:,:,2]**2)**0.5\n",
    "    uc = np.mean(chroma)\n",
    "    sc = (np.mean((chroma - uc)**2))**0.5\n",
    "\n",
    "    #2nd term\n",
    "    top = np.int(np.round(0.01*l.shape[0]*l.shape[1]))\n",
    "    sl = np.sort(l,axis=None)\n",
    "    isl = sl[::-1]\n",
    "    conl = np.mean(isl[::top])-np.mean(sl[::top])\n",
    "\n",
    "    #3rd term\n",
    "    satur = []\n",
    "    chroma1 = chroma.flatten()\n",
    "    l1 = l.flatten()\n",
    "    for i in range(len(l1)):\n",
    "        if chroma1[i] == 0: satur.append(0)\n",
    "        elif l1[i] == 0: satur.append(0)\n",
    "        else: satur.append(chroma1[i] / l1[i])\n",
    "\n",
    "    us = np.mean(satur)\n",
    "\n",
    "    uciqe = c1 * sc + c2 * conl + c3 * us\n",
    "\n",
    "    # UIQM\n",
    "    p1 = 0.0282\n",
    "    p2 = 0.2953\n",
    "    p3 = 3.5753\n",
    "\n",
    "    #1st term UICM\n",
    "    rg = rgb[:,:,0] - rgb[:,:,1]\n",
    "    yb = (rgb[:,:,0] + rgb[:,:,1]) / 2 - rgb[:,:,2]\n",
    "    rgl = np.sort(rg,axis=None)\n",
    "    ybl = np.sort(yb,axis=None)\n",
    "    al1 = 0.1\n",
    "    al2 = 0.1\n",
    "    T1 = np.int(al1 * len(rgl))\n",
    "    T2 = np.int(al2 * len(rgl))\n",
    "    rgl_tr = rgl[T1:-T2]\n",
    "    ybl_tr = ybl[T1:-T2]\n",
    "\n",
    "    urg = np.mean(rgl_tr)\n",
    "    s2rg = np.mean((rgl_tr - urg) ** 2)\n",
    "    uyb = np.mean(ybl_tr)\n",
    "    s2yb = np.mean((ybl_tr- uyb) ** 2)\n",
    "\n",
    "    uicm =-0.0268 * np.sqrt(urg**2 + uyb**2) + 0.1586 * np.sqrt(s2rg + s2yb)\n",
    "\n",
    "    #2nd term UISM (k1k2=8x8)\n",
    "    Rsobel = rgb[:,:,0] * filters.sobel(rgb[:,:,0])\n",
    "    Gsobel = rgb[:,:,1] * filters.sobel(rgb[:,:,1])\n",
    "    Bsobel = rgb[:,:,2] * filters.sobel(rgb[:,:,2])\n",
    "\n",
    "    Rsobel=np.round(Rsobel).astype(np.uint8)\n",
    "    Gsobel=np.round(Gsobel).astype(np.uint8)\n",
    "    Bsobel=np.round(Bsobel).astype(np.uint8)\n",
    "\n",
    "    Reme = eme(Rsobel)\n",
    "    Geme = eme(Gsobel)\n",
    "    Beme = eme(Bsobel)\n",
    "\n",
    "    uism = 0.299 * Reme + 0.587 * Geme + 0.114 * Beme\n",
    "\n",
    "    #3rd term UIConM\n",
    "    uiconm = logamee(gray)\n",
    "\n",
    "    uiqm = p1 * uicm + p2 * uism + p3 * uiconm\n",
    "    return uiqm,uciqe\n",
    "\n",
    "def eme(ch,blocksize=8):\n",
    "\n",
    "    num_x = math.ceil(ch.shape[0] / blocksize)\n",
    "    num_y = math.ceil(ch.shape[1] / blocksize)\n",
    "    \n",
    "    eme = 0\n",
    "    w = 2. / (num_x * num_y)\n",
    "    for i in range(num_x):\n",
    "\n",
    "        xlb = i * blocksize\n",
    "        if i < num_x - 1:\n",
    "            xrb = (i+1) * blocksize\n",
    "        else:\n",
    "            xrb = ch.shape[0]\n",
    "\n",
    "        for j in range(num_y):\n",
    "\n",
    "            ylb = j * blocksize\n",
    "            if j < num_y - 1:\n",
    "                yrb = (j+1) * blocksize\n",
    "            else:\n",
    "                yrb = ch.shape[1]\n",
    "            \n",
    "            block = ch[xlb:xrb,ylb:yrb]\n",
    "\n",
    "            blockmin = np.float(np.min(block))\n",
    "            blockmax = np.float(np.max(block))\n",
    "\n",
    "            # # old version\n",
    "            # if blockmin == 0.0: eme += 0\n",
    "            # elif blockmax == 0.0: eme += 0\n",
    "            # else: eme += w * math.log(blockmax / blockmin)\n",
    "\n",
    "            # new version\n",
    "            if blockmin == 0: blockmin+=1\n",
    "            if blockmax == 0: blockmax+=1\n",
    "            eme += w * math.log(blockmax / blockmin)\n",
    "    return eme\n",
    "\n",
    "def plipsum(i,j,gamma=1026):\n",
    "    return i + j - i * j / gamma\n",
    "\n",
    "def plipsub(i,j,k=1026):\n",
    "    return k * (i - j) / (k - j)\n",
    "\n",
    "def plipmult(c,j,gamma=1026):\n",
    "    return gamma - gamma * (1 - j / gamma)**c\n",
    "\n",
    "def logamee(ch,blocksize=8):\n",
    "\n",
    "    num_x = math.ceil(ch.shape[0] / blocksize)\n",
    "    num_y = math.ceil(ch.shape[1] / blocksize)\n",
    "    \n",
    "    s = 0\n",
    "    w = 1. / (num_x * num_y)\n",
    "    for i in range(num_x):\n",
    "\n",
    "        xlb = i * blocksize\n",
    "        if i < num_x - 1:\n",
    "            xrb = (i+1) * blocksize\n",
    "        else:\n",
    "            xrb = ch.shape[0]\n",
    "\n",
    "        for j in range(num_y):\n",
    "\n",
    "            ylb = j * blocksize\n",
    "            if j < num_y - 1:\n",
    "                yrb = (j+1) * blocksize\n",
    "            else:\n",
    "                yrb = ch.shape[1]\n",
    "            \n",
    "            block = ch[xlb:xrb,ylb:yrb]\n",
    "            blockmin = np.float(np.min(block))\n",
    "            blockmax = np.float(np.max(block))\n",
    "\n",
    "            top = plipsub(blockmax,blockmin)\n",
    "            bottom = plipsum(blockmax,blockmin)\n",
    "\n",
    "            m = top/bottom\n",
    "            if m ==0.:\n",
    "                s+=0\n",
    "            else:\n",
    "                s += (m) * np.log(m)\n",
    "\n",
    "    return plipmult(w,s)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "c3e0de64",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "c:\\users\\plt\\.conda\\envs\\py37\\lib\\site-packages\\ipykernel_launcher.py:17: DeprecationWarning: `np.int` is a deprecated alias for the builtin `int`. To silence this warning, use `int` by itself. Doing this will not modify any behavior and is safe. When replacing `np.int`, you may wish to use e.g. `np.int64` or `np.int32` to specify the precision. If you wish to review your current use, check the release note link for additional information.\n",
      "Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations\n",
      "c:\\users\\plt\\.conda\\envs\\py37\\lib\\site-packages\\ipykernel_launcher.py:47: DeprecationWarning: `np.int` is a deprecated alias for the builtin `int`. To silence this warning, use `int` by itself. Doing this will not modify any behavior and is safe. When replacing `np.int`, you may wish to use e.g. `np.int64` or `np.int32` to specify the precision. If you wish to review your current use, check the release note link for additional information.\n",
      "Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations\n",
      "c:\\users\\plt\\.conda\\envs\\py37\\lib\\site-packages\\ipykernel_launcher.py:48: DeprecationWarning: `np.int` is a deprecated alias for the builtin `int`. To silence this warning, use `int` by itself. Doing this will not modify any behavior and is safe. When replacing `np.int`, you may wish to use e.g. `np.int64` or `np.int32` to specify the precision. If you wish to review your current use, check the release note link for additional information.\n",
      "Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations\n",
      "c:\\users\\plt\\.conda\\envs\\py37\\lib\\site-packages\\ipykernel_launcher.py:105: DeprecationWarning: `np.float` is a deprecated alias for the builtin `float`. To silence this warning, use `float` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.float64` here.\n",
      "Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations\n",
      "c:\\users\\plt\\.conda\\envs\\py37\\lib\\site-packages\\ipykernel_launcher.py:106: DeprecationWarning: `np.float` is a deprecated alias for the builtin `float`. To silence this warning, use `float` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.float64` here.\n",
      "Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations\n",
      "c:\\users\\plt\\.conda\\envs\\py37\\lib\\site-packages\\ipykernel_launcher.py:152: DeprecationWarning: `np.float` is a deprecated alias for the builtin `float`. To silence this warning, use `float` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.float64` here.\n",
      "Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations\n",
      "c:\\users\\plt\\.conda\\envs\\py37\\lib\\site-packages\\ipykernel_launcher.py:153: DeprecationWarning: `np.float` is a deprecated alias for the builtin `float`. To silence this warning, use `float` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.float64` here.\n",
      "Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations\n"
     ]
    }
   ],
   "source": [
    "path='./output_U60/'#要改\n",
    "\n",
    "\n",
    "sumuiqm, sumuciqe = 0.,0.\n",
    "sumniqe=0.\n",
    "N=0\n",
    "\n",
    "path_list = os.listdir(path)\n",
    "path_list.sort(key=lambda x:int(x.split('.')[0]))\n",
    "\n",
    "\n",
    "for item in path_list:\n",
    "    \n",
    "     try:\n",
    "        impath=path+item\n",
    "\n",
    "        imgx= cv2.imread(impath)\n",
    "        #imgx=cv2.resize(imgx,(256,256))\n",
    "        uiqm,_ = nmetrics(imgx)\n",
    "        uciqe=getUCIQE(imgx)\n",
    "        niqe_num=niqe(imgx)\n",
    "        \n",
    "        sumuiqm=sumuiqm+uiqm\n",
    "        sumuciqe=sumuciqe+uciqe\n",
    "        sumniqe=sumniqe+niqe_num\n",
    "        N=N+1\n",
    "     except :\n",
    "        print ('wrong')\n",
    "        pass\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "a81d99f9",
   "metadata": {},
   "outputs": [],
   "source": [
    "muiqm = sumuiqm/N\n",
    "muciqe = sumuciqe/N\n",
    "mniqe=sumniqe/N"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "0c7eaddb",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "uiqm: 0.42787031493747646\n"
     ]
    }
   ],
   "source": [
    "print(\"uiqm:\",muiqm)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "f2f9b4a2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "uciqe: 0.934137956464307\n"
     ]
    }
   ],
   "source": [
    "print(\"uciqe:\",muciqe)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "0802560c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "niqe: 4.748310884205675\n"
     ]
    }
   ],
   "source": [
    "print(\"niqe:\",mniqe)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "977f2dd1",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4c099e18",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fb69f2f8",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ee650ac9",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9575ab2d",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d08564e2",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "77e4af60",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "41a90892",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "99e75b17",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "35b8d74c",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b378c8a6",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6807ebf7",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8384e4ba",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f00fa93d",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "595f0985",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
